// Copyright (c) <2010> <Playdead>
// This file is subject to the MIT License as seen in the trunk of this repository
// Maintained by: <Kristian Kjems> <kristian.kjems+UnitySVN@gmail.com>

// This class makes sure an operation performed is executed within the scope of 
// Unity engines update loop. This is used by the callback functions from an
// asynchronous operation that although executing on the same thread as Unity
// not necessarily execute within the update scope.

using UnityEngine;
using System.Threading;

public delegate void Operation(object state);
public class SyncedToUpdateOperation
{
    public SyncedToUpdateOperation(Operation work, object context)
    {
        this.work = work;
        this.context = context;
    }
    ~SyncedToUpdateOperation()
    {
        resetEvent.Close();
    }

    public void Start()
    {
        UnityEditor.EditorApplication.update += new UnityEditor.EditorApplication.CallbackFunction(Update);
        resetEvent.WaitOne();
        UnityEditor.EditorApplication.update -= new UnityEditor.EditorApplication.CallbackFunction(Update);
    }

    ManualResetEvent resetEvent = new System.Threading.ManualResetEvent(false);

    Operation work;
    object context;

    private void Update()
    {
        work(context);
        resetEvent.Set();
    }
}